package com.example.rwq_test.designParttern.multiThread.threadSpecificStorage;

/**
 * TODO note
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2022/11/19
 */
public class Log {
    private static final ThreadLocal<ThreadSpecificLog> THREAD_SPECIFIC_LOG_COLLECTION = new ThreadLocal<>();

    /**
     * 写日志
     */
    public static void printIn(String context) {
        getThreadSpecificLog().printIn(context);
    }

    /**
     * 关闭日志
     */
    public static void close() {
        getThreadSpecificLog().close();
    }

    /**
     * 获取线程特有的日志
     * @return {@link ThreadSpecificLog}
     */
    private static ThreadSpecificLog getThreadSpecificLog() {
        ThreadSpecificLog threadSpecificLog = THREAD_SPECIFIC_LOG_COLLECTION.get();
        if (threadSpecificLog == null) {
            //第一次调取本方法，需要新生成并注册一个日志
            threadSpecificLog = new ThreadSpecificLog(Thread.currentThread().getName() + "_log.txt");
            THREAD_SPECIFIC_LOG_COLLECTION.set(threadSpecificLog);
        }
        return threadSpecificLog;
    }
}
